package com.code.translate.utils;

import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ggh
 * @date 2022/7/13
 */
public class StringUtils {
    private final static String SEPARATOR = ",";

    private StringUtils() {
    }

    public static String join(List<String> stringList, String separator) {
        if (CollectionUtils.isEmpty(stringList)) {
            return null;
        }
        if (separator == null) {
            separator = SEPARATOR;
        }
        StringBuilder stringBuilder = new StringBuilder();

        for (String str : stringList) {
            stringBuilder.append(str);
            stringBuilder.append(separator);
        }
        if ("".equalsIgnoreCase(separator)) {
            return stringBuilder.toString();
        }

        return stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
    }

    /**
     * 根据集合拼接字符串
     *
     * @param stringList 待拼接集合
     * @param separator  分隔符
     * @return
     */
    public static String joinObject(List<Object> stringList, String separator) {
        if (CollectionUtils.isEmpty(stringList)) {
            return null;
        }
        if (separator == null) {
            separator = SEPARATOR;
        }
        StringBuilder stringBuilder = new StringBuilder();

        for (Object str : stringList) {
            stringBuilder.append(str);
            stringBuilder.append(separator);
        }

        return stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
    }

    /**
     * 切分字符串
     *
     * @param source    文本
     * @param maxLen    最大长度
     * @param separator 分割符asicc值
     * @return 分割后的集合
     */
    public static List<String> splitString(String source, int maxLen, int separator) {
        List<String> signleTextList = new ArrayList<>(source.length() / maxLen + 1);

        int len = source.length();
        int start = 0;
        int end = maxLen - 1;
        do {
            if (source.charAt(end) == separator) {
                String singleText = source.substring(start, end + 1);
                signleTextList.add(singleText);
                start = end + 1;
                end = end + maxLen;
            } else {
                int endIndex = source.lastIndexOf(separator, end);
                String singleText = source.substring(start, endIndex + 1);
                signleTextList.add(singleText);
                start = endIndex + 1;
                end = endIndex + maxLen;
            }
        } while (end < len);

        if (start != source.length()) {
            String singleText = source.substring(start);
            signleTextList.add(singleText);
        }

        return signleTextList;
    }

    /**
     * 判断是否为空
     *
     * @param str 源字符串
     * @return true或者false
     */
    public static boolean isEmpty(@Nullable Object str) {
        return str == null || "".equals(str);
    }

}
